import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/db'
import { getUserFromRequest } from '@/lib/auth'

export async function GET(request: NextRequest) {
  try {
    // 验证用户身份
    const user = await getUserFromRequest(request)
    if (!user) {
      return NextResponse.json(
        { error: '未授权访问' },
        { status: 401 }
      )
    }

    // 获取分页和搜索参数
    const { searchParams } = new URL(request.url)
    const page = parseInt(searchParams.get('page') || '1')
    const pageSize = parseInt(searchParams.get('pageSize') || '20')
    const search = searchParams.get('search') || ''

    console.log('📝 获取文案列表数据...', { page, pageSize, search })

    // 构建查询条件
    const where: any = {
      status: 'completed'
    }

    // 搜索条件
    if (search) {
      where.OR = [
        { extractedText: { contains: search } },
        { video: {
          OR: [
            { title: { contains: search } },
            { author: { contains: search } },
            { tags: { contains: search } }
          ]
        }}
      ]
    }

    // 计算分页偏移量
    const skip = (page - 1) * pageSize

    // 获取总数
    const totalCount = await prisma.textExtraction.count({
      where
    })

    // 查询分页的文案提取记录
    const textExtractions = await prisma.textExtraction.findMany({
      where,
      include: {
        video: {
          select: {
            id: true,
            videoId: true,
            title: true,
            author: true,
            tags: true,
            createdAt: true
          }
        },
        rewrittenTexts: {
          select: {
            id: true,
            rewrittenText: true,
            style: true,
            tone: true,
            length: true,
            requirements: true,
            createdAt: true
          },
          orderBy: {
            createdAt: 'desc'
          },
          take: 1 // 只取最新的一个改写记录
        }
      },
      orderBy: {
        createdAt: 'desc'
      },
      skip,
      take: pageSize
    })

    console.log(`📊 查询到 ${textExtractions.length} 条文案提取记录，总数: ${totalCount}`)

    // 过滤掉空文案
    const validExtractions = textExtractions.filter(extraction =>
      extraction.extractedText &&
      extraction.extractedText.trim().length > 0
    )

    console.log(`✅ 过滤后有 ${validExtractions.length} 条有效文案`)

    // 计算分页信息
    const totalPages = Math.ceil(totalCount / pageSize)

    // 转换为文案管理格式
    const copywritingItems = validExtractions.map(extraction => {
      const rewrite = extraction.rewrittenTexts[0] // 取最新的改写记录

      return {
        id: extraction.video.id,
        videoId: extraction.video.videoId,
        title: extraction.video.title,
        author: extraction.video.author,
        tags: extraction.video.tags,
        createdAt: extraction.video.createdAt.toISOString(),

        // 原始文案信息
        extractionId: extraction.id,
        extractedText: extraction.extractedText,
        extractionMethod: extraction.method,
        extractionDate: extraction.createdAt.toISOString(),

        // 改写文案信息（如果存在）
        rewriteId: rewrite?.id,
        rewrittenText: rewrite?.rewrittenText,
        rewriteStyle: rewrite?.style,
        rewriteTone: rewrite?.tone,
        rewriteLength: rewrite?.length,
        rewriteRequirements: rewrite?.requirements,
        rewriteDate: rewrite?.createdAt.toISOString()
      }
    })

    const statistics = {
      totalItems: copywritingItems.length,
      withRewrites: copywritingItems.filter(item => item.rewriteId).length,
      withoutRewrites: copywritingItems.filter(item => !item.rewriteId).length
    }

    console.log('📊 统计信息:', statistics)

    return NextResponse.json({
      success: true,
      items: copywritingItems,
      pagination: {
        page,
        pageSize,
        total: totalCount,
        pages: totalPages,
        hasNext: page < totalPages,
        hasPrev: page > 1
      },
      statistics
    })

  } catch (error) {
    console.error('❌ 获取文案列表失败:', error)
    return NextResponse.json(
      { 
        error: '获取数据失败',
        details: error instanceof Error ? error.message : '未知错误'
      },
      { status: 500 }
    )
  }
}
